import { defineStore } from 'pinia';
import axios from 'axios';
import router from '../router';
import request from '../utils/request';

// 用户数据类型定义
export interface User {
  id: number;
  username: string;
  email: string;
  avatar?: string;
  role: 0 | 1;
  created: Date;
}

// 登录请求参数类型
interface LoginParams {
  email: string;
  password: string;
}

// 注册请求参数类型
interface RegisterParams {
  username: string;
  email: string;
  password: string;
  confirmPassword: string;
}

// 定义Store
export const useUserStore = defineStore('user', {
  state: (): {
    currentUser: User | null;
    topExperts: User[];
    loading: boolean;
    error: string | null;
    token: string | null;
  } => ({
    currentUser: null,
    topExperts: [],
    loading: false,
    error: null,
    token: localStorage.getItem('token') // 从本地存储获取token
  }),

  getters: {
    // 判断用户是否登录
    isLoggedIn: (state) => !!state.token,
    
    // 判断用户是否为管理员
    isAdmin: (state) => state.currentUser?.role === 1,
    
    // 判断用户是否为专家
    isExpert: (state) => state.currentUser?.role === 0,
    
    // 获取当前用户ID
    currentUserId: (state) => state.currentUser?.id
  },

  actions: {
    // 设置认证token
    setToken(token: string | null): void {
      this.token = token;
      if (token) {
        localStorage.setItem('token', token);
      } else {
        localStorage.removeItem('token');
      }
    },

    // 用户登录
    async login(params: LoginParams): Promise<void> {
      try {
        this.loading = true;
        this.error = null;
        const response = await axios.post<{
          token: string;
          user: User;
        }>('/api/auth/login', params);
        
        this.setToken(response.data.token);
        this.currentUser = response.data.user;
      } catch (err) {
        this.error = err instanceof Error ? err.message : '登录失败，请检查账号密码';
        console.error('登录错误:', this.error);
        throw err; // 抛出错误，便于组件层处理
      } finally {
        this.loading = false;
      }
    },

    // 用户注册
    async register(params: RegisterParams): Promise<void> {
      try {
        this.loading = true;
        this.error = null;
        await axios.post('/api/auth/register', params);
      } catch (err) {
        this.error = err instanceof Error ? err.message : '注册失败，请检查信息';
        console.error('注册错误:', this.error);
        throw err; // 抛出错误，便于组件层处理
      } finally {
        this.loading = false;
      }
    },

    // 退出登录
    logout(): void {
      this.setToken(null);
      this.currentUser = null;
      router.push('login');
    },

    // 获取当前用户信息
    async fetchCurrentUser(): Promise<void> {
      if (!this.token) return;

      try {
        this.loading = true;
        this.error = null;
        const response = await request.get('/api/users/current');
        this.currentUser = response.data.user;
      } catch (err) {
        console.error('获取当前用户信息失败，可能已过期', err);
        this.logout(); // 令牌无效时自动登出
      } finally {
        this.loading = false;
      }
    },

    // 获取优秀答主
    async fetchTopExperts(limit: number = 5): Promise<void> {
      try {
        this.loading = true;
        this.error = null;
        const response = await axios.get<User[]>(`/api/users/top-experts?limit=${limit}`);
        this.topExperts = response.data;
      } catch (err) {
        this.error = err instanceof Error ? err.message : '获取优秀答主失败';
        console.error('获取优秀答主错误:', this.error);
      } finally {
        this.loading = false;
      }
    },

    // 获取用户详情
    async fetchUserDetail(userId: number): Promise<User | null> {
      if (!userId) return null;

      try {
        this.loading = true;
        this.error = null;
        const response = await axios.get<User>(`/api/users/${userId}`);
        return response.data;
      } catch (err) {
        this.error = err instanceof Error ? err.message : '获取用户详情失败';
        console.error('获取用户详情错误:', this.error);
        return null;
      } finally {
        this.loading = false;
      }
    }
  }
});
    